import re

import pymysql

if __name__ == "__main__":
    db = pymysql.connect(host='localhost', port=3306, user='root',
                         password='123456', charset='utf8', database='dict')
    cur = db.cursor()
    with open('dict.txt', 'r', encoding='utf8') as file:
        # pattern_word = r'\S\s'
        # for row in file:
        #     search_word = re.search(pattern_word, row)
        #     print(search_word.group(), end="|")
        #     print(row[len(search_word.group()): -1].strip())
        sql = 'insert into words (word,mean) values (%s,%s)'
        pattern_word = r'(\w+)\s+(.*)'
        for row in file:
            tup = re.findall(pattern_word, row)[0]
            try:
                cur.execute(sql, tup)
                db.commit()
            except Exception:
                db.rollback()
    cur.close()
    db.close()
